// ip2regionv2
package ip2regionv2

import (
	"fmt"
	"log"

	"strings"
	"time"

	//"xwaf_admin/common"
	"xwaf_admin/ip2regionv2/xdb"

	beego "github.com/beego/beego/v2/server/web"
)

var Iprg *xdb.Searcher

func init() {
	//xdb v2
	//var ip2regionDbPth = common.GetValue("ip2regionDbv2")
	ip2regionDbPth, _ := beego.AppConfig.String("ip2regionDbv2")

	if ip2regionDbPth != "" {
		startTime := time.Now().UnixNano()
		//iprg, err = xdb.NewWithFileOnly(ip2regionDbPth)
		cBuff, err := xdb.LoadContentFromFile(ip2regionDbPth)
		if err != nil {
			log.Printf("[ERROR] init ipdata error: %s\n", err.Error())
			return
		}
		var err2 error
		Iprg, err2 = xdb.NewWithBuffer(cBuff)
		if err != nil {
			fmt.Printf("[ERROR] ip2region failed to create searcher with vector index: %s\n", err2)
			return
		}
		endTime := time.Now().UnixNano()
		log.Printf("init ipdata spent:%.1f ms\n", float64(endTime-startTime)/1000000)
		defer Iprg.Close()
	}
}

type IpInfo struct {
	Country  string
	Region   string
	Province string
	City     string
	ISP      string
}

func IpStrToJson(ipstr string) IpInfo {
	lineSlice := strings.Split(ipstr, "|")
	ipInfo := IpInfo{}
	length := len(lineSlice)
	if length < 5 {
		for i := 0; i <= 5-length; i++ {
			lineSlice = append(lineSlice, "")
		}
	}
	ipInfo.Country = lineSlice[0]
	ipInfo.Region = lineSlice[1]
	ipInfo.Province = lineSlice[2]
	ipInfo.City = lineSlice[3]
	ipInfo.ISP = lineSlice[4]
	return ipInfo
}

func IpToCity(ip string) string {
	ipstr, err := Iprg.SearchByStr(strings.TrimSpace(ip))
	if err != nil {
		return "未知"
	}
	ipinfo := IpStrToJson(ipstr)
	city := ipinfo.City
	if city == "" || city == "0" {
		region := ipinfo.Province
		if region == "" || region == "0" {
			return "未知"
		}
	}
	return city
}

func IpToRegion(ip string) string {
	ipstr, err := Iprg.SearchByStr(strings.TrimSpace(ip))
	if err != nil {
		return "未知"
	}
	ipinfo := IpStrToJson(ipstr)
	city := ipinfo.Region
	if city == "" || city == "0" {
		city = ipinfo.Province
		if city == "" || city == "0" {
			return "未知"
		}
	}
	return city
}
